package com.aiton.bamin.bamindaijiadrier.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.IsMobileNOorPassword;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.BankCardInfo;
import com.aiton.bamin.bamindaijiadrier.model.Sms;
import com.aiton.bamin.bamindaijiadrier.model.Wallet;
import com.aiton.bamin.bamindaijiadrier.widget.OnPasswordInputFinish;
import com.aiton.bamin.bamindaijiadrier.widget.PasswordView;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.utils.EncryptUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;

import cn.qqtheme.framework.picker.AddressPicker;
import cn.qqtheme.framework.util.ConvertUtils;
import cz.msebera.android.httpclient.Header;


public class WalletAdvanceActivity extends ZjbBaseActivity implements View.OnClickListener {

    private Wallet.DatasBean mWallet;
    private TextView mTv_notecase;
    private EditText mEdt_name;
    private EditText mEdt_bankCardNumber;
    private EditText mTv_bank;
    private EditText mEdt_money;
    private BankCardInfo mBankCardInfo;
    private int mStatus = 1;
    private PopEnterPassword mPopEnterPassword;
    private EditText mEdt_bankCity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet_advance);
        init();
    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        mWallet = (Wallet.DatasBean) intent.getSerializableExtra(Constant.INTENT_KEY.WALLET);

    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void findID() {
        mTv_notecase = (TextView) findViewById(R.id.textView_leftVlaue);
        mTv_bank = (EditText) findViewById(R.id.tv_bank);
        mEdt_name = (EditText) findViewById(R.id.edt_name);
        mEdt_bankCardNumber = (EditText) findViewById(R.id.edt_bankCardNumber);
        mEdt_money = (EditText) findViewById(R.id.edt_money);
        mEdt_bankCity = (EditText) findViewById(R.id.edt_bankCity);

    }

    @Override
    protected void initViews() {
        if (mWallet != null) {
            if (mWallet.getDriverName() != null && !TextUtils.isEmpty(mWallet.getDriverName())) {
                mEdt_name.setText(mWallet.getDriverName());
            }
            if (mWallet.getBankCardNumber() != null && !TextUtils.isEmpty(mWallet.getBankCardNumber())) {
                mEdt_bankCardNumber.setText(mWallet.getBankCardNumber());
                getBankName(mWallet.getBankCardNumber());
            }
            mTv_notecase.setText(mWallet.getNotecase() + "");
        }

    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_back).setOnClickListener(this);
        findViewById(R.id.textView_sure).setOnClickListener(this);
        mEdt_bankCity.setOnClickListener(this);
        mEdt_bankCardNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String trim = mEdt_bankCardNumber.getText().toString().trim();
                if (trim.length() >= 16 && trim.length() <= 19) {
                    getBankName(trim);
                } else {
                    mTv_bank.setText("");

                }
            }
        });

    }

    /**
     * 获取银行卡信息
     *
     * @param trim
     */
    private void getBankName(String trim) {
        String url = Constant.Url.CARD_INFO;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.addHeader("apikey", "24a817a30be5937b0d761921e05ad7a4");
        RequestParams params = new RequestParams();
        params.put("cardnum", trim);
        asyncHttpClient.get(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("MainActivity", "银行卡信息: --->>" + s);
                try {
                    mBankCardInfo = GsonUtils.parseJSON(s, BankCardInfo.class);
                    if (mBankCardInfo.getStatus() == 1) {
                        BankCardInfo.DataBean data = mBankCardInfo.getData();
                        String bankname = data.getBankname();
                        mTv_bank.setText(bankname);
                    }

                } catch (Exception e) {
                    Log.e("WalletAdvanceActivity", "银行卡信息解析失败");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.e("MainActivity", "请求失败: --->>");
                Toast.makeText(WalletAdvanceActivity.this, "获取银行卡信息失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.edt_bankCity:
                showAddressChoose();
                break;
            case R.id.textView_sure:
                if (mBankCardInfo != null) {
                    mStatus = mBankCardInfo.getStatus();
                }
                Double notecase = mWallet.getNotecase();
                if (!IsMobileNOorPassword.checkChineseName(mEdt_name.getText().toString().trim())) {
                    mEdt_name.setError("请输入正确的姓名");
                } else if (TextUtils.isEmpty(mEdt_bankCardNumber.getText().toString())) {
                    mEdt_bankCardNumber.setError("银行卡号不能为空");
                } else if (mEdt_bankCardNumber.getText().length() < 16) {
                    mEdt_bankCardNumber.setError("输入的位数不够");
                } else if (mStatus != 1) {
                    mEdt_bankCardNumber.setError("获取银行卡信息失败");
                } else if (TextUtils.isEmpty(mEdt_bankCity.getText().toString().trim())) {
                    mEdt_bankCity.setError("银行归属地不能为空");
                } else if (TextUtils.isEmpty(mEdt_money.getText().toString())) {
                    mEdt_money.setError("提现金额不能为空");
                } else if (Double.parseDouble(mEdt_money.getText().toString()) > notecase) {
                    Toast.makeText(WalletAdvanceActivity.this, "提现金额不能大于总余额", Toast.LENGTH_SHORT).show();
                }else if(Double.parseDouble(mEdt_money.getText().toString()) < 100){
                    Toast.makeText(WalletAdvanceActivity.this, "提现金额不能小于100元", Toast.LENGTH_SHORT).show();

                } else {
                    mPopEnterPassword = new PopEnterPassword(WalletAdvanceActivity.this, "提现", "￥" + mEdt_money.getText().toString().trim());
                    // 显示窗口
                    mPopEnterPassword.showAtLocation(WalletAdvanceActivity.this.findViewById(R.id.activity_wallet_advance),
                            Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                }

                break;

        }
    }

    /**
     * 输入支付密码
     *
     * @author lining
     */
    public class PopEnterPassword extends PopupWindow {

        private PasswordView pwdView;

        private View mMenuView;

        private Activity mContext;


        public PopEnterPassword(final Activity context, String way, String money) {

            super(context);

            this.mContext = context;

            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            mMenuView = inflater.inflate(R.layout.pop_enter_password, null);

            pwdView = (PasswordView) mMenuView.findViewById(R.id.pwd_view);

            TextView mTv_way = (TextView) mMenuView.findViewById(R.id.tv_way);
            TextView mTv_forget_password = (TextView) mMenuView.findViewById(R.id.tv_forget_password);
            final TextView mTv_money = (TextView) mMenuView.findViewById(R.id.tv_money);

            mTv_way.setText(way);
            mTv_money.setText(money);
            mTv_forget_password.setVisibility(View.VISIBLE);
            mTv_forget_password.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(WalletAdvanceActivity.this, "忘记密码", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(WalletAdvanceActivity.this,ChangePasswordActivity.class);
                    intent.putExtra(Constant.INTENT_KEY.TYPE,Constant.TYPE.WALLET);
                    intent.putExtra(Constant.INTENT_KEY.WALLET,mWallet);
                    startActivityTo(intent);
                }
            });

            //添加密码输入完成的响应
            pwdView.setOnFinishInput(new OnPasswordInputFinish() {

                @Override
                public void notTheSame(String password) {

                }

                @Override
                public void theSamePassword(String password) {
                }

                @Override
                public void inputAgain(String password) {

                    putWithdrawDeposit(password);
//                    Toast.makeText(WalletAdvanceActivity.this, password, Toast.LENGTH_SHORT).show();
                    dismiss();

                }
            });


            // 监听X关闭按钮
            pwdView.getImgCancel().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

            // 监听键盘上方的返回
            pwdView.getVirtualKeyboardView().getLayoutBack().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

            // 设置SelectPicPopupWindow的View
            this.setContentView(mMenuView);
            // 设置SelectPicPopupWindow弹出窗体的宽
            this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            // 设置SelectPicPopupWindow弹出窗体的高
            this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            // 设置SelectPicPopupWindow弹出窗体可点击
            this.setFocusable(true);
            // 设置SelectPicPopupWindow弹出窗体动画效果
            this.setAnimationStyle(R.style.pop_add_ainm);
            // 实例化一个ColorDrawable颜色为半透明
            ColorDrawable dw = new ColorDrawable(0x66000000);
            // 设置SelectPicPopupWindow弹出窗体的背景
            this.setBackgroundDrawable(dw);

        }
    }

    /**
     * 提现
     *
     * @param password
     */
    private void putWithdrawDeposit(String password) {
        String password4Encrypt = EncryptUtils.encryptSHA256ToString(password);
        showLoadingDialog();
        String url = Constant.Url.ADD_DRAW_MONEY;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("driverId", mWallet.getDriverId());
        params.put("password", password4Encrypt);
        params.put("money", mEdt_money.getText().toString().trim());
        params.put("bankCardNumber", mEdt_bankCardNumber.getText().toString().trim());
        params.put("bankName", mTv_bank.getText().toString().trim());
        params.put("bankCity", mEdt_bankCity.getText().toString().trim());
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("WalletAdvanceActivity", "提现信息: --->>" + s);

                try {
                    Sms sms = GsonUtils.parseJSON(s, Sms.class);
                    if (sms.getStatus() == 0) {

                        showSuccessDialog();
                    } else {
                        showFialDialog(sms.getMes());
                    }
                    cancelLoadingDialog();

                } catch (Exception e) {
                    Toast.makeText(WalletAdvanceActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show();
                    cancelLoadingDialog();

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                cancelLoadingDialog();
                Toast.makeText(WalletAdvanceActivity.this, "数据获取失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showSuccessDialog() {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, "提交成功，3个工作日内进行转账", "确定");
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                finishTo();
                Intent intent = new Intent(Constant.BROADCASTCODE.WALLET);
                sendBroadcast(intent);
                singleBtnDialog.dismiss();
            }
        });
        singleBtnDialog.show();
    }

    private void showFialDialog(String mes) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, mes, "确定");
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
            }
        });
        singleBtnDialog.show();
    }

    /**
     * 地址选择器
     */
    private void showAddressChoose() {
        try {
            ArrayList<AddressPicker.Province> data = new ArrayList<AddressPicker.Province>();
            String json = ConvertUtils.toString(getAssets().open("city.json"));
            data.addAll(JSON.parseArray(json, AddressPicker.Province.class));
            AddressPicker picker = new AddressPicker(this, data);
            picker.setHideCounty(true);

            picker.setSelectedItem("福建", "厦门");
            picker.setOnAddressPickListener(new AddressPicker.OnAddressPickListener() {
                @Override
                public void onAddressPicked(AddressPicker.Province province, AddressPicker.City city, AddressPicker.County county) {
                    if (county == null) {
                        mEdt_bankCity.setText(province.getAreaName() + "  " + city.getAreaName());

                    } else {
                        mEdt_bankCity.setText(province.getAreaName() + "  " + city.getAreaName() + "  " + county.getAreaName());

                    }
                }
            });
            picker.show();
        } catch (Exception e) {
            Toast.makeText(this, "出错了", Toast.LENGTH_SHORT).show();
        }
    }
}
